#!/bin/bash
#
# a simplistic VDS unit test: create VM, log into it as a user, and destroy it.

VDSCLIENT=/opt/dtvtools/vdsClient.py

vmId=loginUT

$VDSCLIENT 0 create /dev/null vmId=$vmId vmName=loginUT memSize=256 macAddr=aa:bb:dd:dd:aa:bb display=vnc hda=/images/igor.qcow2

echo Waiting for VM...
vmstatus=WaitForLaunch
while [ "$vmstatus" == WaitForLaunch -o "$vmstatus" == "Powering Up" ]; do
  sleep 1
  vmstatus=`$VDSCLIENT 0 getVmStats $vmId | grep Status | sed 's/.*= //'`
done
if [ "$vmstatus" != Up -a "$vmstatus" != Running -a "$vmstatus" != "Powering up" ]; then
  echo VM is $vmstatus
  echo Error creating VM >&2
  exit 1
fi

sleep 2
userbefore=`$VDSCLIENT 0 getVmStats $vmId | grep username | sed 's/.*= //'`
echo User before: $userbefore

newuser=Danken
nc -U /tmp/$vmId.interpreter.socket << EOF
guestAgent.dr._activeUser = '$newuser'
EOF

echo Wait to notice Login
while [ "$userafter" != "$newuser" ]; do
  userafter=`$VDSCLIENT 0 getVmStats $vmId | grep username | sed 's/.*= //'`
  echo -n .
  sleep 1
done

echo userafter: $userafter

$VDSCLIENT 0 destroy $vmId
if [ "$userafter" == "$newuser" ]; then
  echo Test successful
  exit 0
else
  echo test failed
  exit 1
fi
